package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.reposltory.StudnetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

@Controller
public class StudentController {
    @Autowired
    private StudnetRepository studnetRepository;

//    private static Map<String,Student> students =new HashMap<>();
//    static{
//        Student s1 =new Student("1","tony");
//        students.put(s1.getId(),s1);
//        Student s2 =new Student("2","jerry");
//        students.put(s2.getId(),s2);
//    }
    @RequestMapping("list")
    public String list(ModelMap map){
        map.put("studentList",studnetRepository.findAll());
        return "list";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        studnetRepository.deleteById(id);
        return "redirect:/list";
    }
    @RequestMapping("create")
    public String create(){
        return "create";
    }
    @RequestMapping("save")
    public String save(Student s){
        //System.out.println(s.getName());
        if(s.getId()==null){
           s.setId(UUID.randomUUID().toString());
        }
        studnetRepository.save(s);
        return "redirect:/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map){
        Student s= studnetRepository.getReferenceById(id);
        map.put("student",s);
        return "update";
    }
}
